package result

import (
	"fmt"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpx"
	"google.golang.org/grpc/status"
	"mall/common/xerr"
	"net/http"
)

func SendHttp(r *http.Request, w http.ResponseWriter, resp interface{}, err error) {
	if err == nil {
		// 成功返回
		response := NewSuccessResponse(resp)
		httpx.WriteJson(w, http.StatusOK, response)
	} else {
		// 错误返回
		errcode := xerr.ServerError
		errmsg := "服务器开小差啦，稍后再来试一试"

		causeErr := errors.Cause(err)            // err类型
		if e, ok := causeErr.(*xerr.Error); ok { //自定义错误类型
			//自定义CodeError
			errcode = e.GetCode()
			errmsg = e.GetMsg()
		} else {
			if gstatus, ok := status.FromError(causeErr); ok { // grpc err错误
				grpcCode := uint32(gstatus.Code())
				errcode = grpcCode
				errmsg = gstatus.Message()
			}
		}

		logx.WithContext(r.Context()).Errorf("[api-err] : %+v", err)
		httpx.WriteJson(w, http.StatusBadRequest, NewErrorResponse(errcode, errmsg))
	}
}

// ParamErrorResult http 参数错误返回
func ParamErrorResult(r *http.Request, w http.ResponseWriter, err error) {
	errMsg := fmt.Sprintf("%s ,%s", xerr.NewErrorWithCode(xerr.InvalidParams), err.Error())
	logx.Infof("请求参数错误: err: %v", err)
	httpx.WriteJson(w, http.StatusBadRequest, NewErrorResponse(xerr.InvalidParams, errMsg))
}
